package com.ruike.alisurface.utils;

import android.annotation.SuppressLint;
import android.content.Context;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.bean.AppInfoBean;
import com.voodoo.lib_frame.base.BaseView;
import com.voodoo.lib_frame.httpTools.DownloadUtil;
import com.voodoo.lib_utils.L;

import java.io.File;
import java.util.Locale;

/**
 * Author：voodoo
 * CreateTime：2021/11/12 012 下午 13:44:54
 * Description：APK升级工具类
 */
public class UpdataApkUtils {

    private static UpdataApkUtils updataApkUtils;

    int lastProgress = 0;

    public static UpdataApkUtils getInstance() {
        if (updataApkUtils == null) {
            synchronized (UpdataApkUtils.class) {
                if (updataApkUtils == null) {
                    updataApkUtils = new UpdataApkUtils();
                }
            }
        }
        return updataApkUtils;
    }

    /**
     * 检查是否有版本更新
     *
     * @param appInfoBean 传入的版本信息
     * @return true 有更新     false 没有版本更新
     */
    public boolean hasUpdata(AppInfoBean appInfoBean) {
        if (appInfoBean != null) {
            AppInfoBean.DataBean data = appInfoBean.getData();
            if (data != null && !data.getDownloadUrl().isEmpty()) {
                // 获取版本号，分别将其格式化
                String serviceVersionStr = data.getVersion().replace(".", "").replace("-", "").replace("_", "");
                String myVersionStr = BuildConfig.VERSION_NAME.replace(".", "").replace("-", "").replace("_", "");

                int serviceVersion = 0;
                int myVersion = 0;
                try {
                    // 再将版本号转换成Integer进行比较
                    serviceVersion = Integer.parseInt(serviceVersionStr);
                    myVersion = Integer.parseInt(myVersionStr);
                } catch (NumberFormatException e) {
                    L.e("当前回传版本号异常");
                    showMsg("当前回传版本号异常");
                    return false;
                }
                return serviceVersion > myVersion;
            }
        }
        return false;
    }

    /**
     * 开始下载APK
     *
     * @param downloadUrl apk的URL下载地址
     */
    public void downloadNewApk(Context context, String downloadUrl) {
        if (!downloadUrl.isEmpty()) {

            @SuppressLint("SdCardPath")
            File apkFile = new File("/sdcard/Download/");
            boolean mkdirs = apkFile.mkdirs();
            String destFileName = "mainNewApp.apk";

            downApk(1, "", 0); // 开始下载
            DownloadUtil.getInstance().download(downloadUrl, apkFile.getPath(), destFileName, new BaseView() {
                @Override
                public void onStarted(String loadingStr) {
                }

                @Override
                public void onLoading(long total, long current) {
                }

                @Override
                public void onComplete() {
                }

                @Override
                public void onErrorTip(String errorStr) {
                }

                @Override
                public void onSuccess(String requestUrl, String requestJsonStr) {
                }

                @Override
                public void onFailure(String requestUrl, String requestMsg) {
                }

                @Override
                public void onError(String requestUrl, String errorMsg) {
                }

                @Override
                public void onError(String requestUrl, String errorMsg, String data) {
                }

                @Override
                public void onException(Exception exception) {
                }

                @Override
                public void onDownloadSuccess(String requestUrl, File file) {
                    downApk(3, "", 0); // 下载完成
                    L.i(String.format("下载成功：%s", file.getPath()));
                    APPUtils.installApk(context, file);
                }

                @Override
                public void onDownloading(String requestUrl, long total, long progress) {
                    if ((int) progress != lastProgress) {
                        downApk(2, String.format(Locale.ENGLISH, "%.2f", total / 1024.0 / 1024), (int) progress); // 下载完成
                        lastProgress = (int) progress;
                        L.i(String.format("下载中：%s", progress));
                    }
                }

                @Override
                public void onDownloadFailed(String requestUrl, Exception e) {
                    downApk(3, "", 0);
                    L.i(String.format("下载失败：%s", e.toString()));
                    showMsg("下载失败");
                }
            });
        } else {
            showMsg("传入的下载Url为空");
        }
    }

    /**
     * 展示消息
     *
     * @param msg 要展示的消息内容
     */
    private void showMsg(String msg) {
        if (onUpdataListener != null) {
            ThreadUtils.postUI(new Runnable() {
                @Override
                public void run() {
                    onUpdataListener.onShowMsg(msg);
                }
            });
        }
    }

    /**
     * 下载的监听回调
     *
     * @param state           状态 1：开始下载  2：下载中  3：下载完成
     * @param apkSize         APK包大小
     * @param currentProgress 当前进度百分比
     */
    private void downApk(int state, String apkSize, int currentProgress) {
        if (onUpdataListener != null) {
            ThreadUtils.postUI(new Runnable() {
                @Override
                public void run() {
                    if (state == 1) {
                        onUpdataListener.onDownloadApkStart();
                    } else if (state == 2) {
                        onUpdataListener.onDownloadingApk(apkSize, currentProgress);
                    } else {
                        onUpdataListener.onDownloadApkComplete();
                    }
                }
            });
        }
    }

    public OnUpdataListener onUpdataListener;

    public void setOnUpdataListener(OnUpdataListener onUpdataListener) {
        this.onUpdataListener = onUpdataListener;
    }

    public interface OnUpdataListener {
        /**
         * 展示消息
         *
         * @param msg 要展示的消息内容
         */
        void onShowMsg(String msg);

        /**
         * 开始下载
         */
        void onDownloadApkStart();

        /**
         * 下载中
         */
        void onDownloadingApk(String apkSize, int currentProgress);

        /**
         * 下载完成
         */
        void onDownloadApkComplete();

    }

}
